/**
 * common/config
 */

import Vue from 'vue';
import Promise from 'bluebird';

import TTXS from './ttxs';

// Bluebird config
Promise.config({
    // allow cancellation
    cancellation: true
});

// api base config
Vue.apiRoot = '/api';
Vue.http.defaults.baseURL = Vue.apiRoot;
Vue.http.interceptors.response.use(res => res, err => {
    // Cancel class (axios.Cancel)
    // https://github.com/tc39/proposal-cancelable-promises
    if(err && err.__CANCEL__) {
        let cancel = err;

        err = new Error('Canceled: ' + err.message);

        err._defaultPrevented = true;
        err.__CANCEL__ = true;
        err.cancel = cancel;
    }

    // http(axios) error
    const response = err.response;
    if(response) {
        const data = response.data || {};
        const msg = data.message || err.message;

        err = new Error(msg);
        err.response = response;
        err.status = response.status || 500;
    }

    // default error handle
    err._defaultPrevented = err._defaultPrevented || false;
    err.preventDefault = function() {
        err._defaultPrevented = true;
    };
    setTimeout(() => {
        if(!err._defaultPrevented) {
            TTXS.showError(err);
        }
    }, 0);

    throw err;
});
